package com.iamteer.hist.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.iamteer.hist.dao.ProductDao;
import com.iamteer.hist.entity.Product;

/**
 * Servlet implementation class ProductHistory
 */
@WebServlet("/ProductHistory")
public class ProductList extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ProductList() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ProductDao dao = new ProductDao();
		List<Product> list = dao.findAll();
		
		response.setContentType("text/html;charset=utf-8");
		PrintWriter writer = response.getWriter();
		String html = "";
		html += "<html>";
		html += "<head>";
		html += "<title>所有商品列表</title>";
		html += "</head>";
		html += "<body>";
		html += "<table border='1' align='center' width='600px'>";
		html += "<tr>";
		html += "<th>编号</th><th>商品名称</th><th>商品型号</th><th>商品价格</th>";
		html += "</tr>";
		if (list != null) {
			for (Product p : list) {
				html += "<tr>";
				html += "<td>"+p.getId()+"</td><td><a href='" + request.getContextPath() + "/ProductDetail?id=" + p.getId() +"'>" +p.getProName()+"</a></td><td>"+p.getProType()+"</td><td>"+p.getPrice()+"</td>";
				html += "</tr>";
			}
		}
		html += "</table>";
		
		//浏览过的商品
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if ("prodHist".equals(cookie.getName())) {
					html += "最近浏览过的商品:<br/>";
					String prodHist = cookie.getValue();
					String[] ids = prodHist.split(",");
					for (String id : ids) {
						Product p = dao.findById(id);
						html += "" + p.getId() + "&nbsp;" + p.getProName() + "&nbsp;" + p.getProType() + "&nbsp;" +p.getPrice() + "<br/>";
					}
				} else {

				}
			}
		}
		
		
		html += "</body>";
		html += "</html>";
		writer.write(html);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
